package cn.myCoils;

import cn.tcp.TcpNewUtil;

public class CoilService implements Runnable {
	private CoilTask2[] coilTask2s;
	private TcpNewUtil tnu = new TcpNewUtil();

	public CoilService(CoilTask2[] coilTasks) {
		this.coilTask2s = coilTasks;
	}
    public CoilService()
    {}
	public void StartService(CoilTask2[] coilTask2s) {
		this.coilTask2s = coilTask2s;
		Thread th=new Thread(this);
		th.start();
	}

	public void StartService() {
		if (coilTask2s == null) {
			throw new RuntimeException(
					"CoilTask is null, please inject coilTask2 first");
		} else {
			StartService(coilTask2s);
		}
	}

	@Override
	public void run() {

		try {
			for (int i = 0; i < coilTask2s.length; i++) {
				// 打开开关
	            tnu.ControlSwitch(coilTask2s[i].getDecid(),
						coilTask2s[i].getSwitchid(), coilTask2s[i].isWriteValue());
			     System.out.println("  启动任务，执行顺序 ："+i +" 设备id:"+coilTask2s[i].getDecid()+" 开关id:"+coilTask2s[i].getSwitchid());
                //通过返回值，来判断是开启成功
					if (i > 0 && i < coilTask2s.length) {
						// 正常开关办法。
						tnu.ControlSwitch(coilTask2s[i-1].getDecid(),
								coilTask2s[i-1].getSwitchid(), false);
					// 其余 是正常开关办法。
					if (i > 0 && i < coilTask2s.length) {
						System.out.println("将上一个开关："+(i-1)+" 关掉 设备id:"+coilTask2s[i-1].getDecid()+" 开关id:"+coilTask2s[i-1].getSwitchid());
						tnu.ControlSwitch(coilTask2s[i-1].getDecid(),
								coilTask2s[i-1].getSwitchid(), false);
					}
				}

				// 线程休息一会吧。
				Thread.sleep(coilTask2s[i].getDelay());
				// 关闭最后开关
				if (i == coilTask2s.length - 1) {
					// 最后一个开关直接关闭
					System.out.println("关闭最后一个开关");
					tnu.ControlSwitch(coilTask2s[i].getDecid(),coilTask2s[i].getSwitchid(), false);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
